#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define jinzhi 16

typedef struct
{
	int* base;
	int* top;
	int StackSize;
}SqStack;

int Init_SqStack(SqStack* S)
{

	S->base = (int*)malloc(MAXSIZE * sizeof(int));
	if (!S->base)
	{
		printf("该顺序栈分配空间失败!\n");
		return ERROR;
	}
	S->top = S->base;
	S->StackSize = MAXSIZE;
	printf("该顺序栈初始化成功!\n");
	return OK;
}

int Push_SqStack(SqStack* S,int &e)
{
	if (S->top - S->base == S->StackSize)
	{
		printf("该顺序栈已满!\n");
		return ERROR;
	}
	*S->top = e;
	S->top++;
	return OK;
}

int Pop_SqStack(SqStack* S,int &e)
{
	if (S->base == S->top)
	{
		printf("该顺序栈已空!\n");
		return ERROR;
	}
	S->top--;
	e = *S->top;
	printf("出栈的元素为:%d\n", e);
	return OK;
}

int SqStack_Empty(SqStack* S)
{
	if (S->top == S->base)
	{
		printf("该顺序栈已空\n");
		return 0;
	}
	else
	{
		printf("该顺序栈不为空\n");
		return 1;
	}
}

void Traverse_SqStack(SqStack* S)
{
	int* elem=S->base;
	if (S->top == S->base)
	{
		printf("栈为空，无法遍历\n");
	}
	else
	{
		while (elem < S->top)
		{
			printf("%d ", *elem);
			elem++;
		}
		printf("\n");
	}
}

void Clear_SqStack(SqStack* S)
{
	if (S->base)
	{
		S->top = S->base;
		printf("该顺序栈已被清空!\n");
	}		
	else
	{
		printf("该顺序栈不存在，无法清空!\n");
	}
}


void Destory_SqStack(SqStack* S)
{
	if (S->base)
	{
		free(S->base);
		S->StackSize = 0;
		S->base = S->top = NULL;
		printf("该顺序栈已被销毁!\n");
	}
	else
	{
		printf("该顺序栈不存在，无法销毁!\n");
	}
}

void Length_SqStack(SqStack* S)
{
	if (S->base&&(*S->base))
	{
		int i = S->top - S->base;
		printf("该顺序栈的长度为:%d\n", i);
	}
	else
	{
		printf("该顺序栈不存在!\n");
	}
}


void Convert_jinzhi(int n)
{
	SqStack Q;
	Init_SqStack(&Q);
	int temp = n;
	while (temp)
	{
		int l = temp % jinzhi;
		Push_SqStack(&Q,l);
		temp = temp / jinzhi;
	}
	while (SqStack_Empty(&Q))
	{
		int i;
		Pop_SqStack(&Q, i);
	}
}



int main()
{
	SqStack S;
	printf("      栈     \n");
	printf("1.初始化栈\n");
	printf("2.入栈\n");
	printf("3.出栈\n");
	printf("4.判断栈空\n");
	printf("5.遍历栈\n");
	printf("6.清空栈\n");
	printf("7.销毁栈\n");
	printf("8.求顺序栈长度\n");
	printf("9.进制转换:\n");
	printf("0.退出操作:\n");
	while (1)
	{
		int n = 0;
		int x = 0;
		int e = 0;	
		printf("请选择对应操作:");
		scanf("%d", &n);
		switch (n)
		{
		case 0:
			x = 1;
			break;
		case 1:
			Init_SqStack(&S);
			break;
		case 2:
			printf("请输入栈元素:");
			scanf("%d", &e);
			Push_SqStack(&S,e);
			break;
		case 3:
			Pop_SqStack(&S, e);
			break;
		case 4:
			SqStack_Empty(&S);
			break;
		case 5:
			Traverse_SqStack(&S);
			break;
		case 6:
			Clear_SqStack(&S);
			break;
		case 7:
			Destory_SqStack(&S);
			break;
		case 8:
			Length_SqStack(&S);
			break;
		case 9:
			printf("将十进制数转化为%d进制:", jinzhi);
			scanf("%d", &e);
			Convert_jinzhi(e);
			break;
		}
		if (x == 1)
			break;
	}
	return 0;
}